package api

import (
	"gitee.com/liuxiaowei123/vblog-1.1/app/token"
	"gitee.com/liuxiaowei123/vblog-1.1/app/token/impl"
	"gitee.com/liuxiaowei123/vblog-1.1/ioc"
	"gitee.com/liuxiaowei123/vblog-1.1/response"
	"github.com/gin-gonic/gin"
)

const AppName = "tokenapihandler"

func init() {
	ioc.IocApiHandler().Registry(&TokenApiHandler{})
}

// 定义api handler
type TokenApiHandler struct {
	tksvc token.TokenService
}

func (t *TokenApiHandler) Init() {
	t.tksvc = ioc.IocController().Get(impl.AppName).(token.TokenService)
}
func (t *TokenApiHandler) Name() string {
	return AppName
}

func NewTokenApiHandler(ts token.TokenService) *TokenApiHandler {
	return &TokenApiHandler{
		tksvc: ts,
	}
}

// 给TokenApiHandler添加路由
func (t *TokenApiHandler) Registry(r gin.IRouter) {
	r.POST("/token", t.Login)
	r.DELETE("/token", t.Logout)

}

// 处理Login请求
func (t *TokenApiHandler) Login(c *gin.Context) {
	// 获取用户数据
	tklr := token.NewLoginRequest()
	err := c.BindJSON(tklr)
	if err != nil {
		// c.JSON(http.StatusBadRequest, err)
		response.Failed(c, err)
		return
	}

	// 处理请求
	tk, err := t.tksvc.Login(c.Request.Context(), tklr)
	if err != nil {
		// c.JSON(http.StatusBadRequest, err)
		response.Failed(c, err)
		return
	}

	// 写入token到setcookie中
	c.SetCookie(token.TOKEN_COOKIE_NAME, tk.AccessToken, 0, "/", "localhost", false, true)

	// 返回响应
	// c.JSON(http.StatusOK, tk)
	response.Success(c, tk)
}

func (t *TokenApiHandler) Logout(c *gin.Context) {}
